package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 黄军艳
 * @version 1.0
 * @date 2024/12/24  9:04
 */
@Controller
@RequestMapping("/main")
public class ChangePwdConntroller extends BaseController {
    private static final Logger LOGGER =
            LoggerFactory.getLogger(StorageRecordController.class);

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/changePwd")
    public String toPwd(){
        return "sys/changePwd";
    }

    //查重
    @GetMapping("/oldPasswordCheck")
    @ResponseBody
    public Object oldPasswordCheck(@RequestParam("oldPassword") String oldPassword){
        Map<String,Object> map=new HashMap<>();
        SysUser sys= session(Constants.SESSION_USER);
        try {
            SysUser sysUser=sysUserService.findById(sys.getId());
            if (oldPassword.equals(sysUser.getPassword())){
                map.put("pass",1);
            }else {
                map.put("pass",0);
            }
        }catch (Exception e) {
            LOGGER.error("ChangePwdConntroller 中的 doPwd 方法执行发生错误。 ", e);
            map.put("pass",-1);
            map.put("error","系统繁忙，请稍后再试");
        }
        return map;
    }

    @PostMapping("/changePwd")
    public String changePwd(@RequestParam("password") String password){
        SysUser sysUser=session(Constants.SESSION_USER);
        try {
            boolean ok=sysUserService.updatePwd(sysUser.getId(),password);
            if (ok){
                return redirect("/login.jsp");
            }else {
                return redirect("sys/changePwd");
            }
        }catch (Exception e) {
            LOGGER.error("ChangePwdConntroller 中的 changePwd 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
    }
}
